package com.hockeo.tinygds;

import java.lang.reflect.Field;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.ShortBlob;
import com.hockeo.tinygds.annotation.TShortBlob;
import com.hockeo.tinygds.error.TNotLoadableException;

/**
 * Special field for binary data.
 *
 * @version $Id$
 * @author jjanke
 */
public class TFieldBinary extends TField<byte[]>
{
  protected TFieldBinary( TinyGDSFactory factory, Field field )
  {
    super( factory, field );
  }

  @Override
  public Object getValueForDatastore( Object objInstance )
  {
    byte[] abyte = getValue( objInstance );

    if ( abyte == null )
      return null;

    if ( getRealField().isAnnotationPresent( TShortBlob.class ) )
      return new ShortBlob( abyte );
    else
      return new Blob( abyte );
  }

  @Override
  protected byte[] transformDatastoreValue( Object objDatastoreValue )
  {
    if ( objDatastoreValue instanceof ShortBlob )
      return ( (ShortBlob) objDatastoreValue ).getBytes();
    else if ( objDatastoreValue instanceof Blob )
      return ( (Blob) objDatastoreValue ).getBytes();

    throw TNotLoadableException.cannotConvertValue( objDatastoreValue, getRealField() );
  }
}
